package com.szl.group.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.szl.group.common.model.PageInfo;
import com.szl.group.common.model.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * description:
 * author: shenxiaolong
 * date: 2020/6/20
 */
@Slf4j
public class BaseController<S extends IService<T>, T> {

    @Autowired
    protected S service;

    /**
     * 根据id来查询.
     */
    @GetMapping("/getOne/{id}")
    public ResponseEntity getById(@PathVariable Integer id) {
        return ResponseEntity.ok(R.success(service.getById(id)));
    }

    /**
     * 查询列表.
     */
    @GetMapping("/list")
    public ResponseEntity getList(T t) {
        return ResponseEntity.ok(R.success(service.list(new QueryWrapper<>(t))));
    }

    /**
     * 分页查询.
     */
    @GetMapping("/page")
    public ResponseEntity getByPaginate(Long pageNumber, Long pageSize, T t) {
        if (null != pageNumber && null != pageSize) {
            return ResponseEntity.ok(R.success(new PageInfo((Page) service
                    .page(new Page<>(pageNumber, pageSize), new QueryWrapper<>(t)))));
        } else {
            return ResponseEntity.ok(R.success(new PageInfo((Page) service
                    .page(new Page<>(), new QueryWrapper<>(t)))));
        }
    }

    /**
     * 新增一条记录.
     */
    @PostMapping("/insert")
    public ResponseEntity insert(@RequestBody T entity) {
        return ResponseEntity.ok(R.success(service.save(entity)));
    }

    @PostMapping("/batch")
    public ResponseEntity insertBatch(@RequestBody List<T> entityList) {
        return ResponseEntity.ok(R.success(service.saveBatch(entityList)));
    }

    /**
     * 根据id修改一条记录.
     */
    @PutMapping("/update")
    public ResponseEntity update(@RequestBody T entity) {
        return ResponseEntity.ok(R.success(service.updateById(entity)));
    }

    /**
     * 根据id 批量修改记录.
     */
    @PutMapping("/batch")
    public ResponseEntity updateBatch(@RequestBody List<T> entityList) {
        return ResponseEntity.ok(R.success(service.updateBatchById(entityList)));
    }

    /**
     * 根据id删除一条记录.
     */
    @DeleteMapping("/delete/{id}")
    public ResponseEntity delete(@PathVariable Integer id) {
        log.info("start delete  item batch with id '{}'", id);
        return ResponseEntity.ok(R.success(service.removeById(id)));
    }
}